package com.example.onenetdht11.util;

import android.os.Build;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.onenetdht11.Contests;
import com.example.onenetdht11.MainActivity;
import com.example.onenetdht11.Token;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

@RequiresApi(api = Build.VERSION_CODES.O)
public class OneNetUtils {
    MainActivity ma;
    public OneNetUtils(MainActivity mainActivity) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        this.ma = mainActivity;
    }
    String version = "2018-10-31";
    String resourceName = "products/506494";
    String expirationTime = System.currentTimeMillis() / 1000 + 100 * 24 * 60 * 60 + "";
    String signatureMethod = Token.SignatureMethod.SHA1.name().toLowerCase();
    String accessKey = "5Hv3M749iaxQn3SCN4Gk4N/5NSRi6ZAItFni3pi2xDY=";
    Token token = new Token();
    String toke = token.assembleToken(version, resourceName, expirationTime, signatureMethod, accessKey);

    //获取最新数据
     public String getInfo(String dataStream) {
         String reponse = null;
         try {
             URL url = new URL("http://api.heclouds.com/devices/" +Contests.DeviceID +
                     "/datapoints?&datastream_id=" + dataStream);
             HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
             httpURLConnection.setConnectTimeout(15 * 1000);
             httpURLConnection.setRequestMethod("GET");
             //按照Onenet要求，请求报文头中封装apikey
             httpURLConnection.setRequestProperty("Authorization", toke);
             if (httpURLConnection.getResponseCode() == 200) {//如果返回码是200,网络正常
                 InputStream inputStream = httpURLConnection.getInputStream();
                 BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));//字节数组输出流
                 int len = 0;
                 String line;
                 while ((line = br.readLine()) != null) {
                     reponse = line;
                 }
                 com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(reponse);
                 JSONObject jsonObject1=jsonObject.getJSONObject("data");
                 JSONObject jsonArray = jsonObject1.getJSONArray("datastreams").getJSONObject(0);
                 JSONArray jsonArray1 = jsonArray.getJSONArray("datapoints");
                 reponse = jsonArray1.getJSONObject(0).getString("value");

                 inputStream.close();
                 br.close();
                 Log.i("onenet", "getInfo: " + reponse);
             } else {
                 Toast.makeText(ma, "网络异常" + httpURLConnection.getResponseCode(), Toast.LENGTH_SHORT).show();
             }
         } catch (IOException e) {
             Toast.makeText(ma, "数据获取异常", Toast.LENGTH_LONG).show();
             e.printStackTrace();
         }
         return reponse;
     }

    //获取datatime作为起始点的参数
    public ArrayList<String> getInfo(String dataStream,String datatime) {
        String reponse = null;
        ArrayList<String> arrayList = new ArrayList<>();
        try {
            URL url = new URL("http://api.heclouds.com/devices/" + Contests.DeviceID +
                    "/datapoints?datastream_id=" + dataStream + "&start=" + datatime + "&limlt=100/");

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(15 * 1000);
            httpURLConnection.setRequestMethod("GET");
            //按照Onenet要求，请求报文头中封装apikey
            httpURLConnection.setRequestProperty("Authorization", toke);
            if (httpURLConnection.getResponseCode() == 200) {//如果返回码是200,网络正常
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));//字节数组输出流
                String line;
                while ((line = br.readLine()) != null) {
                    reponse = line;
                }
                System.out.println(reponse);
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(reponse);
                JSONObject jsonObject1=jsonObject.getJSONObject("data");
                if (jsonObject1.getJSONArray("datastreams").toString().equals("[]")){
                    arrayList = null;
                    inputStream.close();
                    br.close();
                    return arrayList;
                } else {
                    JSONObject jsonArray = jsonObject1.getJSONArray("datastreams").getJSONObject(0);
                    JSONArray jsonArray1 = jsonArray.getJSONArray("datapoints");
                    if (jsonArray1 != null) {
                        for (int x = 0; x < jsonArray1.size(); x++) {
                            arrayList.add(jsonArray1.getJSONObject(x).getString("value"));
                        }
                    }
                    inputStream.close();
                    br.close();
                    // Log.i("onenet", "getInfo: " + reponse);
                }
            } else {
                Looper.prepare();

                Toast.makeText(ma, "网络异常" + httpURLConnection.getResponseCode(), Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        } catch (IOException e) {
            Toast.makeText(ma, "数据获取异常", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
        return arrayList;
    }

    public ArrayList<Double> getdoubleInfo(String dataStream,String datatime) {
        String reponse = null;
        ArrayList<Double> arrayList = new ArrayList<>();
        try {
            URL url = new URL("http://api.heclouds.com/devices/" + Contests.DeviceID +
                    "/datapoints?datastream_id=" + dataStream + "&start=" + datatime + "&limlt=10");

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(15 * 1000);
            httpURLConnection.setRequestMethod("GET");
            //按照Onenet要求，请求报文头中封装apikey
            httpURLConnection.setRequestProperty("Authorization", toke);
            if (httpURLConnection.getResponseCode() == 200) {//如果返回码是200,网络正常
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));//字节数组输出流
                String line;
                while ((line = br.readLine()) != null) {
                    reponse = line;
                }
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(reponse);
                JSONObject jsonObject1=jsonObject.getJSONObject("data");
                if (jsonObject1.getJSONArray("datastreams").toString().equals("[]")){
                    arrayList = null;
                    inputStream.close();
                    br.close();
                    return arrayList;
                }else {
                    JSONObject jsonArray = jsonObject1.getJSONArray("datastreams").getJSONObject(0);
                    JSONArray jsonArray1 = jsonArray.getJSONArray("datapoints");
                    if (jsonArray1 != null) {
                        for (int x = 0; x < jsonArray1.size(); x++) {
                            arrayList.add(jsonArray1.getJSONObject(x).getDouble("value"));
                        }
                    }
                    inputStream.close();
                    br.close();
                }


            } else {
                Looper.prepare();
                Toast.makeText(ma, "网络异常", Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        } catch (IOException e) {
            Toast.makeText(ma, "数据获取异常", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
        return arrayList;
    }

    /**
     *
     * @param dataStream    数据类型
     * @param startTime     起始时间
     * @param endTime       终止时间
     * @return              时间段内的数据
     */
    public ArrayList<Double> getDoubleInfoByTimer(String dataStream,String startTime, String endTime) {
        String reponse = null;
        ArrayList<Double> arrayList = new ArrayList<>();
        try {
            URL url = new URL("http://api.heclouds.com/devices/" + Contests.DeviceID +
                    "/datapoints?datastream_id=" + dataStream + "&start=" + startTime + "&end=" + endTime + "&limlt=100");

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(15 * 1000);
            httpURLConnection.setRequestMethod("GET");
            //按照Onenet要求，请求报文头中封装apikey
            httpURLConnection.setRequestProperty("Authorization", toke);
            if (httpURLConnection.getResponseCode() == 200) {//如果返回码是200,网络正常
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));//字节数组输出流
                String line;
                while ((line = br.readLine()) != null) {
                    reponse = line;
                }
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(reponse);
                JSONObject jsonObject1=jsonObject.getJSONObject("data");
                System.out.println("jsonObject" + jsonObject);
                if (jsonObject1.getJSONArray("datastreams").toString().equals("[]")){
                    arrayList = null;
                    inputStream.close();
                    br.close();
                    return arrayList;
                }else {
                    JSONObject jsonArray = jsonObject1.getJSONArray("datastreams").getJSONObject(0);
                    JSONArray jsonArray1 = jsonArray.getJSONArray("datapoints");
                    if (jsonArray1 != null) {
                        for (int x = 0; x < jsonArray1.size(); x++) {
                            arrayList.add(jsonArray1.getJSONObject(x).getDouble("value"));
                        }
                    }
                    inputStream.close();
                    br.close();
                }


            } else {
                Looper.prepare();
                Toast.makeText(ma, "网络异常", Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        } catch (IOException e) {
            Toast.makeText(ma, "数据获取异常", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
        return arrayList;
    }

    public ArrayList<String> getInfo(String dataStream,String datatime,String enddatatime) {
        String reponse = null;
        ArrayList<String> arrayList = new ArrayList<>();
        try {
            URL url = new URL("http://api.heclouds.com/devices/" + Contests.DeviceID +
                    "/datapoints?datastream_id=" + dataStream + "&start=" + datatime + "&end=" + enddatatime + "&limlt=10");

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(15 * 1000);
            httpURLConnection.setRequestMethod("GET");
            //按照Onenet要求，请求报文头中封装apikey
            httpURLConnection.setRequestProperty("Authorization", toke);
            if (httpURLConnection.getResponseCode() == 200) {//如果返回码是200,网络正常
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));//字节数组输出流
                String line;
                while ((line = br.readLine()) != null) {
                    reponse = line;
                }
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(reponse);
                JSONObject jsonObject1=jsonObject.getJSONObject("data");
                if (jsonObject1.getJSONArray("datastreams").toString().equals("[]")){
                    arrayList = null;
                    inputStream.close();
                    br.close();
                    return arrayList;
                }else {
                    JSONObject jsonArray = jsonObject1.getJSONArray("datastreams").getJSONObject(0);
                    JSONArray jsonArray1 = jsonArray.getJSONArray("datapoints");

                    //Log.i("reponse", "getInfo: " + jsonArray1.getJSONObject(0));

                    if (jsonArray1 != null) {
                        for (int x = 0; x < jsonArray1.size(); x++) {
                            arrayList.add(jsonArray1.getJSONObject(x).getString("value"));
                        }
                    }
                    inputStream.close();
                    br.close();
                }
            } else {
                Toast.makeText(ma, "网络异常", Toast.LENGTH_LONG).show();
            }
        } catch (IOException e) {
            Toast.makeText(ma, "数据获取异常", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
        return arrayList;
    }

    public ArrayList<String> endgetinfo(String dataStream,String enddatatime) {
        String reponse = null;
        ArrayList<String> arrayList = new ArrayList<>();
        try {
            URL url = new URL("http://api.heclouds.com/devices/" + Contests.DeviceID +
                    "/datapoints?datastream_id=" + dataStream + "&end=" + enddatatime + "&limlt=10");

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(15 * 1000);
            httpURLConnection.setRequestMethod("GET");
            //按照Onenet要求，请求报文头中封装apikey
            httpURLConnection.setRequestProperty("Authorization", toke);
            if (httpURLConnection.getResponseCode() == 200) {//如果返回码是200,网络正常
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));//字节数组输出流
                String line;
                while ((line = br.readLine()) != null) {
                    reponse = line;
                }
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(reponse);
                JSONObject jsonObject1=jsonObject.getJSONObject("data");
                JSONObject jsonArray = jsonObject1.getJSONArray("datastreams").getJSONObject(0);
                JSONArray jsonArray1 = jsonArray.getJSONArray("datapoints");

                //Log.i("reponse", "getInfo: " + jsonArray1.getJSONObject(0));

                if (jsonArray1 != null) {
                    for (int x = 0; x < jsonArray1.size(); x++) {
                        arrayList.add(jsonArray1.getJSONObject(x).getString("value"));
                    }
                }
                inputStream.close();
                br.close();
            } else {
                Toast.makeText(ma, "网络异常", Toast.LENGTH_LONG).show();
            }
        } catch (IOException e) {
            Toast.makeText(ma, "数据获取异常", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
        return arrayList;
    }
    //上传dataToPost数据
    public void postData(String dataStream,String dataToPost){
        Toast.makeText(ma,"开始上传",Toast.LENGTH_SHORT).show();
        String dataNew = new String(",;" + dataStream + "," + dataToPost);
        String reponse = null;
        byte data[] = dataNew.getBytes();

        try {
            URL url = new URL("http://api.heclouds.com/devices/" + Contests.DeviceID +
                    "/datapoints?type=5");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(15*1000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Authorization",Contests.APIKey);
            httpURLConnection.setRequestProperty("Content-length",String.valueOf(data.length));
            httpURLConnection.setChunkedStreamingMode(5);
            httpURLConnection.connect();
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data);
            outputStream.flush();
            outputStream.close();
            if (httpURLConnection.getResponseCode() == 200) {//如果返回码是200,网络正常
                InputStream inputStream = httpURLConnection.getInputStream();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();//字节数组输出流
                int len = 0;
                byte buff[] = new byte[1024];
                while (inputStream.read(buff) != -1) {
                    byteArrayOutputStream.write(buff, 0, len);
                }
                inputStream.close();
                byteArrayOutputStream.close();

                reponse = buff.toString();
                Log.i("post", "postData: " + reponse);
            } else {
                Toast.makeText(ma, "网络异常", Toast.LENGTH_LONG).show();
            }
        } catch (IOException e) {
            Toast.makeText(ma, "数据获取异常", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    public void postCmd(String command){
        Toast.makeText(ma,"开始发送命令",Toast.LENGTH_LONG).show();
        String reponse = null;
        byte[] data = command.getBytes();
        try {
            URL url = new URL("http://api.heclouds.com/v1/synccmds?device_id=" + Contests.DeviceID + "&timeout=30");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(15*1000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Authorization", toke);
            httpURLConnection.setRequestProperty("Content-Type", "application/xml");
            httpURLConnection.setChunkedStreamingMode(5);
            httpURLConnection.connect();

            OutputStream outputStream = httpURLConnection.getOutputStream();

            outputStream.write(data);
            outputStream.flush();
            outputStream.close();

            if (httpURLConnection.getResponseCode() == 200) {//如果返回码是200,网络正常

                System.out.println(command);
                Log.i("post", "postData: " + reponse);

                Toast.makeText(ma,"上传成功",Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(ma, "网络异常", Toast.LENGTH_LONG).show();
            }
        } catch (IOException e) {
            Toast.makeText(ma, "上传失败", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }
}
